import { useState } from "react";
import "./index.css";
import { loginApi } from "./quest.js";
const App = () => {
  const [formData, setFormData] = useState({
    username: "",
    password: "",
    checkPass: "",
  });
  const [isShow, setShow] = useState(false);
  const setState = ({ target }) => {
    setFormData({ ...formData, [target.name]: target.value });
    console.log(target.name, target.value);
  };
  const subimt = () => {
    // isShow false表示登录,true表示注册
    const { checkPass, password, username } = formData;
    //1.首先通过isShow判断是登录还是注册

    //2.校验值
    if (!username) {
      return alert("用户名不许为空");
    }
    if (!password) {
      return alert("密码不许为空");
    }
    if (isShow) {
      if (checkPass !== password) {
        return alert("两次密码不一致");
      }
    }
    //3.再次提交
    loginApi(formData).finally(() => {
      alert(`${isShow ? "注册" : "登录"}成功`);
    });
    console.log("提交");
  };
  const { username, password, checkPass } = formData;
  return (
    <>
      <label htmlFor="">
        <span>用户名</span>
        <input
          value={username}
          onChange={setState}
          name="username"
          type="text"
        />
      </label>
      <label style={!isShow ? { display: "none" } : { display: "block" }}>
        <span>密码</span>
        <input
          value={checkPass}
          onChange={setState}
          name="checkPass"
          type="checkPass"
        />
      </label>
      <label htmlFor="">
        <span>确认密码</span>
        <input
          value={password}
          onChange={setState}
          name="password"
          type="text"
        />
      </label>

      {/* 切换登录注册 */}
      <button onClick={() => setShow(!isShow)}>
        {isShow ? "登录" : "注册"}
      </button>
      {/* 提交 */}
      <button onClick={subimt}>subimt</button>
    </>
  );
};

export default App;
